The next topic is retries
and duplicate delivery. Regardless of whether you
use Pub/Sub or Cloud tasks, your code must be prepared to handle the same
message twice, or even the same message
twice at the same time. Here are some reasons
why this might happen. Pub/Sub is a distributed
system and it might happen that it delivers
the same message twice due to how
it was designed. Even if a timeout occurs and
Pub/Sub retries the message, your code might have
already processed the message fully
prior to the timeout. Your own container might exit while it is
handling a request, for example, due to
memory pressure. In your case, Pub/Sub retries the message even
if the message has been fully processed already. If you retry and handle
the same message twice, this might be fine. However, sometimes it has
real-world consequences. In this example, the
message contained an order. The shipment service received the order message twice and
shipped the order twice. I'm pretty sure that
this would make an auditor quite unhappy. If you publish a
message to a topic, Pub/Sub assigns it a
unique message ID. Even if a subscription
retries the message, the message ID remains the same. Let's take a look at two
things you can do to make your code resilient
against retries. The first thing is
record message IDs that have been processed. You can use the unique
message ID to record the processing state of
the message in a database. If you receive a message, all you have to do is check you've already processed
the message before. Use a lease to guard against
parallel processing. Recording what messages
have been processed prevents most occurrences
of duplicate execution. However, there is still a
small chance you might receive a retry while you are already processing
the same message. To solve this problem, you can use a lease to handle
the message exclusively. This is how this works. As you receive the message, persist the message ID with
the state in progress, and store a timestamp of
when the lease expires. If you fully handle the message, update the record with
the state completed. Reject all messages that have an existing lease
that did not expire.